<template>
  <div class="content">
    <my-newsearch></my-newsearch>

    <cate-gorize
      ref="cateGorize"
      :type="type"
      :first_list="first_list"
      :second_list="second_list"
      @toggleTab="toggleTab"
      :currentClass="currentClass"
      @selectSecond="change"
      @selectSecond2="selectSecond"
      :newSecondIndex="newSecondIndex"
    >
      <div
        slot="shop"
        :style="{ height: `calc(100vh - 122rpx - 120rpx - ${computeHeight})` }"
      >
        <scroll-view
          scroll-y="true"
          class="all_good_height"
          @scrolltolower="onReachBottoms"
        >
          <div
            class="shop"
            v-for="(item, index) in goods_list"
            :key="index"
            @click="detailPage(index, item.id)"
          >
            <image class="shop-image" :src="item.img" mode="aspectFit"></image>
            <div class="shop-info">
              <div style="display: flex; align-items: center">
                <image
                  v-if="item.datum_activity == '满减'"
                  style="width: 40rpx; height: 24rpx; margin-right: 10px"
                  src="/static/image/manjian.svg"
                ></image> 
                <image
                  v-if="item.datum_activity == '满赠'"
                  style="width: 40rpx; height: 24rpx; margin-right: 10px"
                  src="/static/image/manzeng.svg"
                ></image>
                <span class="title">{{ item.name }}</span>
              </div>
              <div class="shop-info-price" v-if="canshowprice">
                {{ item.showPrice
                }}<text
                  v-if="item.spu.length == 1 && item.spu[0].current_price == 0"
                  style="font-size: 20rpx"
                >
                  /{{ item.spu[0].unit }}</text
                >
                <my-stepper
                  class="shop-info-btn"
                  :val="item.willBuyNum"
                  :min="item.minimum"
                  :limit="item.designated_inventory"
                  :inventory="item.inventory_left"
                  :index="index"
                  @plus="addAction(item, index, $event)"
                  @minus="subAction"
                  @showKey="
                    $refs.keyboard.open(
                      item.is_standard,
                      index,
                      item.minimum,
                      item.inventory_left,
                      item.designated_inventory
                    )
                  "
                >
                </my-stepper>
              </div>
              <div class="shop-info-tips">
                <div class="flex-center" v-for="(i, index) in item.datum" :key="index">
                  {{ i.title }}
                </div>
              </div>
              <div class="flex-middle">
                <span class="shop-info-rise" v-if="item.minimum > 0"
                  >起订量 :
                  <span style="margin-left: 10rpx">{{ item.minimum }}</span></span
                >
                <span class="shop-info-rise" v-if="item.designated_inventory > 0"
                  >库存 :
                  <span style="margin-left: 10rpx">{{
                    item.inventory_left
                  }}</span></span
                >
              </div>
              <span class="remarks" v-if="item.spu.length == 1">{{
                item.spu[0].describe || ""
              }}</span>  
            </div>
          </div>
          <div class="prompt tonext" v-if="toNext" @click="toNextAction">
            {{ bottomText }}
            <text style="color: red; margin-left: 10rpx">{{
              next_category_name
            }}</text>
          </div>
          <view class="nodata" v-if="goods_list.length == 0">
            <image :src="nodataImg" mode="aspectFit"></image>
            <view>该分类暂时还没有商品~</view>
          </view>
        </scroll-view>
      </div>
    </cate-gorize>
    <my-keyboard ref="keyboard" @confirm="inputPrice"></my-keyboard>
    <my-addcart
      ref="minicart"
      @tabBarTag="changeTabBarTag"
      :canshowprice="canshowprice"
    ></my-addcart>
    <my-tabar ref="tabar" current="1"></my-tabar>
  </div>
</template>

<script>
import { $https } from "@/static/js/request.js";
import MixinShowprice from "@/static/js/mixinshowprice.js";
import CateGorize from "@/components/CateGorize/index.vue";
export default {
  mixins: [MixinShowprice],
  components: {
    CateGorize,
  },
  data() {
    return {
      nodataImg: getApp().globalData.nodataImg,
      loginVolid: null, //是否强制登录
      logo: "",
      showLogo: 0,
      page: 1,
      count: 0,
      current: 0,
      scrollTop: 0,
      first_list: [],
      second_list: [],
      secondIndex: 0,
      goods_list: [],
      pid: null, //当前一级分类id
      category_id: null, //当前二级分类id
      next_category_id: null, //下个二级分类id
      next_category_name: "", //下个二级分类
      toNext: false,
      bottomText: "点击加载",
      indexNavid: null, //从首页导航或者banner过来
      newCategoryId: null, //从首页导航或者banner过来
      flag: true, //onshow是否刷新
      currentClass: 0,
      open: false,
      // #ifdef APP-PLUS
      temp: 100,
      // #endif

      // #ifdef H5 || MP-WEIXIN
      temp: 90,
      // #endif

      type: 1,

      newSecondIndex: 0,
    };
  },
  computed: {
    computeHeight() {
      return this.type == 1 ? "52px" : "75px";
    },
  },
  onLoad(options) {
    this.indexNavid = options.navid;
    this.newCategoryId = options.category_id;
    if (options.navid) {
      this.pid = options.navid;
    }
    if(options.category_id) {
      this.category_id = options.category_id;
    }
    this.loginVolid = !Boolean(
      uni.getStorageSync("loginVolid").is_login_category
    );
  },
  onShow() {
    //先由emit触发，再执行onshow
    uni.$once("updateclassify", (res) => {
      this.flag = false;
    });
    if (this.flag) {
      this.goods_list = [];
      var params = {};
      if (this.pid) {
        Object.assign(params, {
          pid: this.pid,
        });
        this.currentClass = 0;
        this.current = 0;
      }
      if (this.category_id) {
        Object.assign(params, {
          category_id: this.category_id,
        });
      }
      this.getData(1, params, this.secondIndex);
    }
    this.flag = true;
  },
  methods: {
    getData(page, prop, index = 1) {
      this.toNext = false;
      var params = {
        page: page,
        size: 15,
      };
      if (prop) {
        Object.assign(params, prop);
      }
      if (!params.category_id) delete params.category_id;
      $https(
        "GET",
        "getGoodsList",
        params,
        (res) => {
          let data = res.data.data;
          //是否显示logo
          uni.setStorageSync("showLogo", data.auto_watermark);
          uni.setStorageSync("logo", data.site_logo);
          this.showLogo = data.auto_watermark;
          this.logo = data.site_logo;
          this.type = data.type;
          // 设置商品总数
          this.count = data.count;
          // 设置一级分类，当一级分类为0时，赋值给first_list，否则跳过;并且将商品制空
          if (this.first_list.length == 0) {
            this.first_list = res.data.data.first_list;
          }
          // 设置二级分类
          this.second_list = data.second_list;
          // 设置展示的商品名称;处理价格规格sku
          let goods_list = this.changePrice(data.goods_list);
          this.goods_list = this.goods_list.concat(goods_list);

          /**
           * 设置商品最后的文字展示效果
           * 判断条件：
           * 	1、商品数量大于0
           * 	2、当前商品数量是否低于总数量
           * 	3、当前secondIndex低于该二级分类总数 - 1
           * 		3.1、如果是最后一个二级分类时，应展示没有更多了
           */
          if (
            this.goods_list.length > 0 &&
            this.goods_list.length == this.count &&
            this.secondIndex < this.second_list - 1
          ) {
            this.toNext = true;
            this.bottomText = "点击加载";
          } else {
            this.toNext = true;
            this.bottomText = "没有更多了";
            this.next_category_name = "";
            this.next_category_id = null;
          }
          // 如果有这个id，说明是首页导航或者banner来的。默认选中那个分类
          if (this.indexNavid) {
            this.changeFirstCurrent(this.indexNavid);
          }
          // 如果有这个id，说明是首页导航或者banner来的。默认选中二级分类
          if(this.newCategoryId) {
            this.current = this.second_list.findIndex(item=> item.id == this.category_id);
            this.currentClass = this.current;
            index = this.current + 1;
          }
          /**
           * 获取下个二级分类的分类名、二级分类id
           */
          let next = this.second_list[index];
          this.next_category_name = next ? next.title : "";
          this.next_category_id = next ? next.id : null;
          /**
           * 获取一级分类id
           * 刚进入分类页面时，需将一级分类的id赋值给pid，后续操作后pid修改
           */
          if (!this.pid && this.first_list.length) {
            this.pid = this.first_list[0].id;
            this.category_id = this.first_list[0].selfNext[0].id;
          } else {
            let cate_id = this.first_list.filter((item) => item.id == this.pid);
            this.category_id = cate_id[0].selfNext[this.current].id;
          }
          if (this.pid) {
            this.secondIndex = this.first_list.findIndex((item) => {
              return item.id == this.pid;
            });
          }
          this.page = page;
          this.$refs.tabar.changetag(res.data.data.all_cart_num);
        },
        this.loginVolid
      );
    },
    changeFirstCurrent(id) {
      for (let index in this.first_list) {
        if (this.first_list[index].id == id) {
          this.current = 0;
          this.indexNavid = null;
          this.newSecondIndex = index;
          return;
        }
      }
    },
    onReachBottoms() {
      var page = this.page;
      //如果请求到底就请求下一列表
      if (this.goods_list.length < this.count) {
        page++;
        this.getData(
          page,
          {
            pid: this.pid,
            category_id: this.category_id,
          },
          this.current + 1
        );
      } else {
        this.toNext = true;
        if (!this.next_category_id) {
          this.bottomText = "没有更多啦~";
        } else {
          this.bottomText = "点击加载";
        }
      }
    },
    //跳到商品详情
    detailPage(index, id) {
      uni.navigateTo({
        url: `../../subindex/index/shopdetail?id=${id}`,
      });
    },
    //显示小购物车
    showCart(index) {
      var data = this.goods_list[index];
      this.$refs.minicart.open(data);
    },
    //改变底部导航栏购物车tag
    changeTabBarTag(num) {
      this.$refs.tabar.changetag(num);
    },
    //＋
    addAction(item, index, data) {
      if (item.spu.length > 1) {
        this.showCart(index);
      } else {
        var index = data.index,
          min = data.min,
          limit = data.limit,
          inventory = data.inventory,
          val = data.value;
        if (val < min) {
          val = min;
        } else if (limit > 0 && val + 1 >= inventory) {
          //不能超过库存量
          val = inventory;
          uni.showToast({
            icon: "none",
            title: "库存不足",
          });
          return;
        } else {
          val++;
        }
        this.addToCart(
          this.goods_list[index].id,
          this.goods_list[index].spu[0].id,
          val.toFixed(2),
          index
        );
      }
    },
    //-
    subAction(data) {
      var index = data.index,
        min = data.min,
        inventory = data.inventory,
        val = data.value;

      if (val - 1 < min) {
        val = 0;
      } else {
        val--;
      }
      // this.goods_list[data.index].willBuyNum = val;
      this.addToCart(
        this.goods_list[index].id,
        this.goods_list[index].spu[0].id,
        val.toFixed(2),
        index
      );
    },
    //输入数量
    inputPrice(data) {
      var val = Number(data.value),
        index = data.index;
      this.addToCart(
        this.goods_list[index].id,
        this.goods_list[index].spu[0].id,
        val.toFixed(2),
        index
      );
    },
    // 加入购物车
    addToCart(goodsId, spuId, num, index) {
      var options = {
        goods_id: goodsId,
        spu_id: spuId,
        num,
      };
      $https("POSTN", "changeCart", options, (res) => {
        if (res.data.errcode == 0) {
          this.goods_list[index].willBuyNum = Number(num);
          this.$refs.tabar.changetag(res.data.data.all_cart_num);
        } else {
          uni.showToast({
            title: res.data.errmsg,
            icon: "none",
          });
        }
      });
    },

    //处理价格规格sku
    changePrice(data) {
      var array = JSON.parse(JSON.stringify(data));
      for (let i in array) {
        //算出价格范围
        if (array[i].spu.length > 1) {
          var min, max;
          min = array[i].spu[0].market_price;
          if (array[i].spu[1].market_price < min) {
            max = Number(array[i].spu[0].market_price);
            min = Number(array[i].spu[1].market_price);
          } else {
            max = Number(array[i].spu[1].market_price);
            min = Number(array[i].spu[0].market_price);
          }
          for (let y in array[i].spu) {
            if (Number(array[i].spu[y].market_price) < min) {
              min = Number(array[i].spu[y].market_price);
            } else if (Number(array[i].spu[y].market_price) > max) {
              max = Number(array[i].spu[y].market_price);
            }
          }
          let bol1 = array[i].spu.some((e) => {
            return e.current_price == 1;
          });
          let bol2 = array[i].spu.every((e) => {
            return e.current_price == 1;
          });
          let arr = [];
          array[i].spu.forEach((e) => {
            if (e.current_price != 1) {
              arr.push(e.market_price);
            }
          });
          let maxs = Math.max(...arr);
          let mins = Math.min(...arr);
          // console.log(max,min);
          if (bol2) {
            array[i].showPrice = "时价";
          } else if (bol1) {
            array[i].showPrice = `时价~${maxs.toFixed(2)}`;
          } else {
            array[i].showPrice = `￥${mins.toFixed(2)}~${maxs.toFixed(2)}`;
          }
          // array[i].showPrice = `￥${min.toFixed(2)}~${max.toFixed(2)}`;
        } else if (array[i].spu.length == 1) {
          if (array[i].spu[0].activity_price) {
            //活动价
            array[i].showPrice = "￥" + array[i].spu[0].activity_price;
          } else if (array[i].spu[0].current_price == 1) {
            //是时价
            array[i].showPrice = "时价";
          } else {
            array[i].showPrice = "￥" + array[i].spu[0].market_price;
          }
          //只有一个规格时显示起订量、库存
          array[i].minimum = array[i].spu[0].minimum;
          array[i].designated_inventory = array[i].spu[0].inventory_hd
            ? 11
            : array[i].spu[0].designated_inventory;
          array[i].inventory_left =
            array[i].spu[0].inventory_hd || array[i].spu[0].inventory_left;
        }
        array[i].willBuyNum = array[i].num_cart_count;
      }
      return array;
    },

    //点击一级列表
    toggleTab(index) {
      this.secondIndex = index;
      this.goods_list = [];
      this.currentClass = 0;
      this.current = 0;
      this.pid = this.first_list[index].id;
      this.category_id = this.first_list[index].selfNext[0].id; //重设二级id
      this.toNext = false;
      this.getData(1, {
        pid: this.pid,
        category_id: this.category_id,
      });
    },
    toNextAction() {
      // 如果没有下级id，表示不可点击。
      let index = this.current + 1;
      // 如果有下级id，表示可点击。
      if (this.next_category_id) {
        this.selectSecond(this.next_category_id, index);
      }
    },
    /**
     * 点击二级分类时函数
     * id: 二级分类id
     * index: 展示的二级分类下标
     */
    selectSecond(id, index) {
      // 将商品列表制空
      this.goods_list = [];
      // 修改二级分类选中的样式，赋值当前选中的二级分类下标
      this.currentClass = index;
      this.current = index;
      // 将商品下面的提示语隐藏
      this.toNext = false;
      this.change(index);
    },
    // 点击二级分类时根据获取到的二级分类下标获取二级分类id并调用获取商品接口
    change(index) {
      // 将商品列表制空
      this.goods_list = [];
      // 修改二级分类选中的样式，赋值当前选中的二级分类下标
      this.currentClass = index;
      this.current = index;
      // 将商品下面的提示语隐藏
      this.toNext = false;
      // 根据pid匹配一级分类的二级分类列表
      let category_list = this.first_list.filter(
        (item) => item.id == this.pid
      )[0];
      // 获取二级分类id
      let category_id = category_list.selfNext[index]
        ? category_list.selfNext[index].id
        : null;
      this.category_id = category_id;
      this.getData(
        1,
        {
          pid: this.pid,
          category_id: category_id,
        },
        index + 1
      );
    },
  },
  onReady() {
    getApp().setTitle();
  },
};
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  background-color: #f8f9fa;

  .all_good_height {
    height: 100%;
    .shop {
      width: 100%;
      background-color: #fff;
      display: flex;
      align-items: center;
      &-image {
        width: 180rpx;
        height: 180rpx;
        margin: 0 10rpx;
      }
      &-info {
        display: flex;
        width: 340rpx;
        height: 248rpx;
        flex-direction: column;
        border-bottom: 1rpx solid #ebebeb;
        position: relative;
        padding: 32rpx 0 0 0;
        box-sizing: border-box;
        .title {
          width: 300rpx;
          font-family: PingFang SC;
          font-weight: bold;
          font-size: 28rpx;
          height: 28rpx;
          line-height: 28rpx;
          color: #333333;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          overflow: hidden;
          -webkit-line-clamp: 1;
        }
        .remarks {
          width: 300rpx;
          font-family: PingFang SC;
          font-weight: 500;
          font-size: 22rpx;
          height: 22rpx;
          line-height: 22rpx;
          color: #cccccc;
          margin-top: 8rpx;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          overflow: hidden;
          -webkit-line-clamp: 1;
        }
        &-tips {
          display: flex;
          flex-direction: row;
          width: 164rpx;
          overflow: hidden;
          div {
            border: 1rpx solid;
            height: 26rpx;
            padding: 4rpx 5rpx 5rpx 4rpx;
            margin-right: 10rpx;
            border-radius: 4rpx;
            box-sizing: border-box;
            font-size: 18rpx;
            min-width: 48rpx;
            &:first-child {
              color: #f55726;
            }
            &:nth-child(2) {
              color: #40ae36;
            }
          }
        }
        &-rise {
          margin-top: 8rpx;
          font-family: PingFang SC;
          font-weight: 500;
          font-size: 22rpx;
          height: 22rpx;
          line-height: 22rpx;
          color: #cccccc;
          margin-right: 10rpx;
        }
        &-price {
          font-family: PingFang SC;
          font-weight: bold;
          font-size: 32rpx;
          color: #f55726;
          display: flex;
          align-items: center;
          position: relative;
          height: 48rpx;
          line-height: 48rpx;
          margin: 16rpx 0 8rpx;
          .icon {
            font-size: 18rpx;
          }
        }
        &-btn {
          position: absolute;
          bottom: 0;
          right: 0;
        }
      }
    }
    .prompt {
      height: 150rpx;
      line-height: 150rpx;
      text-align: center;
    }
    .tonext {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.nodata {
  z-index: 99;
  height: 500rpx;
}
</style>